<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="发放条件">
                <a-select v-model="sendRule">
                  <a-select-option v-for="(item, index) in giveRuleOptions" :key="index" :value="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="searchSendRuleList">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <!-- 发放规则列表 -->
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <div>
          <a-button type="primary" @click="addRule"> 添加规则 </a-button>
          <a-button style="margin-left: 8px" @click="deleteRules"> 批量删除 </a-button>
        </div>
      </div>
      <a-alert
        :message="`已选择 ${selectedRuleTableNodes.length} 项`"
        type="info"
        style="margin-bottom: 16px"
        v-if="selectedRuleTableNodes.length"
        show-icon
      />
      <a-table
        ref="tableList"
        @mouseleave.native="onMouseLeaveTable"
        :columns="ruleColumns"
        :data-source="dataSource"
        :row-key="(record) => record.id"
        :rowSelection="{ selectedRowKeys: this.selectedRuleTableNodes, onChange: this.onSelectRuleChange }"
        :pagination="{
          total: this.totalCount,
          showSizeChanger: true,
          onChange: this.tablePageChange,
          onShowSizeChange: this.paginationSizeChange,
        }"
        :loading="ruleLoading"
        :customRow="
          (record, index) => {
            return {
              on: {
                mouseenter: (e) => {
                  this.currentRuleRowId = record.id
                },
              },
            }
          }
        "
      >
        <!-- 发放条件 -->
        <span slot="event" slot-scope="text, record">
          <span>{{ record.event | transEvent }}</span>
        </span>
        <!-- 状态 -->
        <div slot="status" slot-scope="status, item">
          <a-switch
            @click="switchChange($event, item)"
            checked-children="开"
            un-checked-children="关"
            :defaultChecked="status == 1 ? true : false"
          />
        </div>
        <!-- 操作按钮 -->
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="handleDelete(record)" size="small">删除</a-button>
        </span>
      </a-table>

      <a-modal
        :title="ruleForm.id ? '编辑规则' : '添加规则'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="showRuleModal"
        @ok="saveRuleInfo"
        @cancel="showRuleModal = false"
      >
        <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" :form="ruleForm">
          <a-form-item label="发放条件：">
            <a-select style="width: 520px" :default-value="ruleForm.event" v-model="ruleForm.event">
              <a-select-option v-for="(item, index) in giveRuleOptions" :key="index" :value="item.value">
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="领取条件：" v-if="ruleForm.event === 5">
            <a-select style="width: 520px" v-model="ruleForm.ext_type">
              <a-select-option v-for="(item, index) in extTypeList" :key="index" :value="item.value">
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="需要积分：" v-show="ruleForm.event == 3">
            <a-input-number :min="0" v-model="ruleForm.amount" />
            <p
              style="
                font-size: 14px;
                font-family: PingFangSC-Regular;
                line-height: 22px;
                color: #f5222d;
                margin-bottom: 0;
              "
            >
              积分不足时可折算现金购买
            </p>
          </a-form-item>
          <a-form-item label="需要现金：" v-show="ruleForm.event == 3">
            <a-input-number :min="0" v-model="ruleForm.money" />
          </a-form-item>
          <a-form-item label="充值金额：" v-show="ruleForm.event == 2">
            <a-input-number :min="0" v-model="ruleForm.amount" />
          </a-form-item>
          <a-form-item label="优惠券选择：">
            <a-select
              style="width: 520px"
              mode="multiple"
              :size="size"
              placeholder="选择优惠券"
              :default-value="ruleForm.coupon_id"
              @popupScroll="popupScroll"
              @change="couponSelectChange"
            >
              <a-select-option v-for="(item, index) in couonList" :value="item.id" :key="index">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="单人每天获取数量：">
            <a-input-number :min="0" style="width: 88px" v-model="ruleForm.day_num" placeholder="" />
          </a-form-item>
          <a-form-item label="单人总获取数量：">
            <a-input-number :min="0" style="width: 88px" v-model="ruleForm.day_count" placeholder="" />
          </a-form-item>
          <a-form-item label="发放次数限制：" v-show="ruleForm.event == 1 || ruleForm.event == 4">
            <a-input-number :min="0" v-model="ruleForm.send_times" />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import pick from 'lodash.pick'
import { STable } from '@/components'
// import SelectCat from './components/selectGoodsCat'
import SelectCat from '@/components/SearchCat/index'
import SelectGoods from '@/components/SearchGoods/index'
import SelectUser from '@/components/SelectUser/SelectUser'
import { getPermission } from '@/api/auth'
import {
  couponList,
  getRuleCoupons,
  addCouponRule,
  getRuleCouponList,
  deleteCouponRule,
  dupdateCouponRule,
  ruleStatus,
} from '@/api/marketing'

const STATUS = {
  1: '显示',
  0: '不显示',
}

const ruleColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '发放条件',
    dataIndex: 'event',
    scopedSlots: {
      customRender: 'event',
    },
  },
  {
    title: '单人每天获取数量',
    dataIndex: 'day_num',
    sorter: (a, b) => a.day_num - b.day_num,
  },
  {
    title: '单人总获取数量：',
    dataIndex: 'day_count',
    sorter: (a, b) => a.day_count - b.day_count,
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '操作',
    dataIndex: 'action',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

export default {
  name: 'ArticleList',
  components: {
    STable,
    SelectCat,
    SelectGoods,
    SelectUser,
  },
  data() {
    return {
      is_saas: false,
      user_id: 0,
      // 权限树
      permissionTree: [],
      // 已选择的权限
      selectedPermission: [],
      modalLoading: false,
      defaultCheckedKeys: [],

      send_visible: false,
      send_data: {},
      send_form: this.$form.createForm(this),
      // 查询条件参数
      queryParam: {
        search_key: null,
        status: 1,
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        console.log(parameter, 'parameter')
        return couponList(parameter)
          .then((res) => {
            console.log('couponList', res)
            this.type_list = res.data.type_list
            this.is_saas = res.data.is_join_saas == 1
            return res.data
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.$refs.table.localLoading = false
          })
      },

      // 选择分类开始
      select_cat_visible: false,
      select_goods_visible: false,
      // 选择分类结束
      selectedRowKeys: [],
      tabIndex: 1,

      activeTab: '1',
      showQrCode: false,
      qrcodeUrl: '',
      sendRule: '',
      // 选择分类结束
      selectedRuleTableNodes: [],
      ruleColumns,
      currentRuleRowId: '',
      ruleLoading: false,
      dataSource: [],
      totalCount: 0,
      pageSize: 10,
      pageNo: 1,
      showRuleModal: false,
      ruleInfo: {},
      ruleForm: {
        event: 1,
        money: 10,
        coupon_id: [],
        day_num: 0,
        day_count: 1,
        send_times: 0,
        amount: 0,
        ext_type: 1,
      },
      couonList: [],
      ruleType: [],

      giveRuleOptions: [
        {
          value: 1,
          text: '分享页面',
        },
        {
          value: 2,
          text: '充值赠送',
        },
        // {
        //   value: 3,
        //   text: '现金积分购买'
        // },
        // {
        //   value: 4,
        //   text: '二维码领取'
        // },
        {
          value: 5,
          text: '新人专享',
        },
      ],

      extTypeList: [
        { value: 1, text: '首次登录' },
        { value: 2, text: '完成首单' },
        { value: 3, text: '完成次单' },
      ],
    }
  },
  watch: {
    sendRule(val) {
      this.getRuleCouponList()
    },
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
    transEvent(val) {
      const arr = ['', '分享页面', '充值赠送', '现金积分购买', '二维码领取', '新人专享']
      return arr[val]
    },
  },
  created() {
    getPermission({}).then((res) => {
      this.permissionTree = res.data
    })
    // this.getRuleCoupons()
    this.getRuleCouponList()
  },
  methods: {
    moment,
    // 开关变换
    async switchChange(val, item) {
      console.log(val, item, '更改规则状态')
      try {
        const res = await ruleStatus({ status: val ? 1 : 0, id: item.id })
        if (res.code != 0) throw res
        this.getRuleCouponList()
        this.$message.success(res.msg)
      } catch (error) {
        this.$message.error(res.msg || '服务器出错')
      }
    },
    // 规则列表
    getRuleCouponList() {
      const parameter = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        event: this.sendRule,
      }
      getRuleCouponList(parameter).then((res) => {
        console.log('=======', res)
        if (!res.code) {
          this.dataSource = res.data.data
          this.totalCount = res.data.totalCount
          this.couonList = res.data.type_list
        }
      })
    },
    // 弹框优惠券列表
    // getRuleCoupons () {
    //   console.log(123)
    //   getRuleCoupons().then((res) => {
    //     if (!res.code) {
    //       this.couonList = res.data.data
    //     }
    //   })
    // },
    // 点击编辑
    handleEdit(record) {
      console.log(record)
      this.ruleForm = JSON.parse(JSON.stringify(record))
      if (typeof this.ruleForm.coupon_id == 'string') {
        this.ruleForm.coupon_id = JSON.parse(this.ruleForm.coupon_id)
      }
      this.ruleForm.event = Number(this.ruleForm.event)
      this.ruleForm.ext_type = Number(this.ruleForm.ext_type)
      this.showRuleModal = true
    },
    handleDelete(record) {
      console.log(record)
      this.$confirm({
        title: '提示',
        content: '确认删除？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          console.log('确认')
          this.requestDeleteRules({ id: [record.id], status: 1 })
        },
        onCancel: () => {
          console.log('取消')
        },
      })
    },
    deleteRules() {
      console.log(this.selectedRuleTableNodes)
      if (!this.selectedRuleTableNodes.length) return
      this.$confirm({
        title: '提示',
        content: '确认删除？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          console.log('确认')
          this.requestDeleteRules({ id: this.selectedRuleTableNodes, status: 1 })
        },
        onCancel: () => {
          console.log('取消')
        },
      })
    },
    requestDeleteRules(params) {
      deleteCouponRule(params).then((res) => {
        console.log(res)
        if (!res.code) {
          this.$message.success('删除成功！')
          this.selectedRuleTableNodes = []
          this.getRuleCouponList()
        }
      })
    },
    // 添加规则
    addRule() {
      this.ruleInfo = {}
      this.ruleForm = {
        event: 1,
        money: 10,
        coupon_id: [],
        day_num: 0,
        day_count: 1,
        send_times: 0,
        amount: 0,
        ext_type: 1,
      }
      this.showRuleModal = true
    },
    // 保存规则数据
    saveRuleInfo() {
      console.log(this.ruleInfo)
      const params = Object.assign({}, this.ruleForm)
      console.log(params)
      params.coupon_id = JSON.stringify(params.coupon_id)
      if (this.ruleForm?.id) {
        dupdateCouponRule(params).then((res) => {
          if (!res.code) {
            this.$message.success('修改成功！')
            this.showRuleModal = false
            // 刷新规则列表
            this.getRuleCouponList()
          }
        })
      } else {
        addCouponRule(params).then((res) => {
          if (!res.code) {
            this.$message.success('添加成功！')
            this.showRuleModal = false
            // 刷新规则列表
            this.getRuleCouponList()
          }
        })
      }
    },
    popupScroll(e) {
      console.log(e)
    },
    // 优惠券选择
    couponSelectChange(e) {
      console.log(e)
      this.ruleForm.coupon_id = e
      console.log(this.ruleForm.coupon_id)
    },
    searchSendRuleList() {
      console.log(this.sendRule)
    },

    onSelectRuleChange(selectedRowKeys) {
      this.selectedRuleTableNodes = selectedRowKeys
    },
    // 分页请求
    tablePageChange(e) {
      console.log(e)
      this.pageNo = e
      this.getRuleCouponList()
    },
    // 分页器页数修改回调
    paginationSizeChange(current, size) {
      console.log(current, size)
      this.pageNo = current
      this.pageSize = size
      this.getRuleCouponList()
    },
    onMouseLeaveTable(e) {
      if (e.relatedTarget && e.relatedTarget.className.indexOf('popover') != -1) {
        return
      }
      this.currentRowId = ''
    },
    // 选择商品分类弹窗
    selectGoodsCatModal() {
      this.select_cat_visible = !this.select_cat_visible
    },
    selectGoodsCatOk(e) {
      console.log(e)
      this.cat_list = e
      this.$nextTick(() => {
        this.form.setFieldsValue({
          cat_id_list: JSON.stringify(e.map((el) => el.id)),
        })
        this.form.setFieldsValue({
          cat_name_list: e.map((el) => el.name).join(),
        })
      })
      // this.selectGoodsCatModal()
    },
    selectGoodsModal() {
      this.select_goods_visible = !this.select_goods_visible
    },
    selectGoodsOk(e) {
      console.log(e)
      var id = []
      for (var i in e) {
        id.push(parseInt(e[i].id))
      }
      this.goods_list = e
      this.$nextTick(() => {
        this.form.setFieldsValue({
          goods_id_list: JSON.stringify(id),
        })
      })
    },
  },
}
</script>

<style lang="less" scoped></style>
